package com.hlx.apiinterface.Controller;

import com.hlx.apiclientsdk.Model.User;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;

import static com.hlx.apiclientsdk.utils.SignUtils.getSign;

@RestController
@RequestMapping("/name")
public class NameController {
    private Set<String> nonceList = new HashSet<>();


    private String secretKey = "asdfghjkl";
    
    @GetMapping("/get")
    public String getNameByGet(String name) {

        return "GET 你的名字是" + name;
    }

    @PostMapping("/post")
    public String getNameByPost(@RequestParam String name) {
        return "POST 你的名字是" + name;
    }
    
    // 验证时间
    public boolean checkTime(long timestamp) {
        long current = System.currentTimeMillis() / 1000;
        return current <= (timestamp + 60);
    }
    
    // 验证nonce
    public boolean checkNonce(String nonce) {
        nonceList.add(nonce); 
        return true;
    }
    
    @PostMapping("/user")
    public String getUserNameByPost(@RequestBody User user, HttpServletRequest request) {
        String accessKey = request.getHeader("accessKey");
        String nonce = request.getHeader("nonce");
        String body = request.getHeader("body");
        String timestamp = request.getHeader("timestamp");
        String sign = request.getHeader("sign");
        
        String checkSign = getSign(body, secretKey);

        if (Long.parseLong(nonce) > 10000) {
            throw new RuntimeException("无权限");
        }

        if (!checkTime(Long.parseLong(timestamp))) {
            throw new RuntimeException("超时不可用");
        }
        
        if (!sign.equals(checkSign)) {
            throw new RuntimeException("无权限");
        }
        
        return "POST 你的名字是" + user.getUsername();
    }
}
